package web;

import beans.LoginStatus;
import beans.User;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import service.UserService;
import utils.ResultUtils;

import java.io.IOException;

@WebServlet("/user/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.获取页面传递的参数
        //username=root&password=123456
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        //2.将页面的参数进行封装,方便将来传递给service层
        User user = new User(username,password);
        //3.调用UserService处理业务逻辑:登录逻辑处理
        UserService us = new UserService();
        User existUser = us.login(user);
        String responseData;
        //4.根据existUser结果来决定响应的信息
        if(existUser != null ){
            //说明已经登录成功
            //a.将用户信息(会话状态)存储中session中
            request.getSession().setAttribute("existUser", existUser);

            //登录成功并且用户勾选了记住我复选框,此时向浏览器写一个cookie
            //该cookie中存储了用户信息
            String autoLogin = request.getParameter("autoLogin");
            if (autoLogin != null && autoLogin.equals("on")){
                Cookie cookie = new Cookie("autoLogin", existUser.getUsername() + "#" + existUser.getPassword());
                cookie.setMaxAge(7*24*60*60);
                cookie.setPath(request.getContextPath());
                response.addCookie(cookie);
            }
            //b.构造登录成功的响应数据
            responseData = ResultUtils.result(LoginStatus.LOGIN_SUCCESS, existUser);
        }else {
            //说明登录失败,构造登录失败的响应数据
            //new User(username, password)构造的是登录失败的 用户名和密码
            responseData = ResultUtils.result(LoginStatus.LOGIN_FAIL,new User(username,password));
        }
        //5.将统一构造的json数据响应给浏览器
        response.getWriter().write(responseData);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
